#include "utils/init.h"
#include "utils/glutil.h"
#include "utils/logger.h"

#include <psp2/kernel/threadmgr.h>

#include <falso_jni/FalsoJNI.h>
#include <so_util/so_util.h>
#include <main.h>
#include "reimpl/controls.h"

int _newlib_heap_size_user = 256 * 1024 * 1024;

#ifdef USE_SCELIBC_IO
int sceLibcHeapSize = 4 * 1024 * 1024;
#endif
#define SCREEN_W 960
#define SCREEN_H 544
so_module so_mod;
jobjectArray JobjectArray;
uint32_t Sleeptime;

DeviceInfo info[]={
[DeviceID]="123456789012345",
[Country]="KR",
[Language]="en",
[MODEL]="PSV",
[MapleC2DMRegistrationID]="",
[Id]="O11019",
[SDKVERSION]="20",
[AppID]="",
[AppName]="MapleLive",
[PackageName]="com.nexonmobile.maplelive.googleplay",
[StoreInfo]="",
};

void SetSleepTime(uint32_t time)
{
   Sleeptime=time;
}

int main_thread(SceSize args, void *argp)
{
	int (* RenderUpdate)(void) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_Render");

    //uint64_t last_render_time = current_timestamp_ms();
  
    Sleeptime=10;
    while (1) 
    {
        controls_poll();
        RenderUpdate();
        gl_swap();
    }

	return 0;
}

int main() {
    soloader_init_all();
    
    // int (* JNI_OnLoad)(void *jvm) = (void *)so_symbol(&so_mod, "JNI_OnLoad");
    // JNI_OnLoad();
    int (* AppInit)(char *,char *,char *) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_Init");
    int (* RenderInit)(void) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_Render_1Init");
    int (* RenderResize)(int,int,int,int) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_Render_1Resize");
	int (* RenderUpdate)(void) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_Render");
	int (* SelectCharacterCB)(int,int,int) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_SelectCharacterCB");
    //int (* SetHttpCheatProcess)(int,int,int) = (void *)so_symbol(&so_mod, "Java_com_nexonmobile_skyproject_jni_Natives_SetHttpCheatProcess");

    JobjectArray=NewObjectArray(&jni,11,"DeviceInfo",NULL);
    for (size_t i = 0; i < 11; i++)
    {
        SetObjectArrayElement(&jni,JobjectArray,i,info[i]);
    }
    AppInit(&jni,NULL,JobjectArray);
    
    SelectCharacterCB(0,0,0);
    debugPrintf("AppInit over \n");

    gl_init();
    //eglSwapInterval(0, 2);
    RenderInit();
    debugPrintf("RenderInit over \n");
    RenderResize(0,0,SCREEN_W,SCREEN_H);
    debugPrintf("RenderResize over \n");

    // ... do some initialization
    SceUID thid = sceKernelCreateThread("main_thread", (SceKernelThreadEntry)main_thread, 0x40,2* 128 * 1024, 0, 0, NULL);
	sceKernelStartThread(thid, 0, NULL);
	return sceKernelExitDeleteThread(0);
}
